using Beaker.OpenCube.Render.Maths;

namespace Beaker.OpenCube.Render.Materials
{
	public sealed class Bitmap
		: TexelSource
	{
		private readonly byte[, ,] _colorMatrix;

		public Bitmap( System.Drawing.Bitmap sourceBitmap )
			: this( sourceBitmap, new System.Drawing.Rectangle( 0, 0, sourceBitmap.Width, sourceBitmap.Height ) )
		{
		}

		public Bitmap( System.Drawing.Bitmap sourceBitmap, System.Drawing.Rectangle rectangle )
			: base( rectangle.Width, rectangle.Height )
		{
			_colorMatrix = new byte[rectangle.Width, rectangle.Height, 3];

			// TODO: Convert to 
			for( int y = rectangle.Top; y < rectangle.Bottom; y++ )
			{
				int u = y - rectangle.Top;

				for( int x = rectangle.Left; x < rectangle.Right; x++ )
				{
					int v = x - rectangle.Left;

					var gdiColor = sourceBitmap.GetPixel( x, y );
					_colorMatrix[u, v, 0] = gdiColor.R;
					_colorMatrix[u, v, 1] = gdiColor.G;
					_colorMatrix[u, v, 2] = gdiColor.B;
				}
			}
		}

		protected override Color GetTexelColor( int u, int v )
		{
			return
				new Color(
					_colorMatrix[u, v, 0] / 255d,
					_colorMatrix[u, v, 1] / 255d,
					_colorMatrix[u, v, 2] / 255d
					);
		}
	}
}